package com.cwz.security.service;

import com.cwz.api.model.LoginUser;
import com.cwz.core.constant.CacheConstants;
import com.cwz.core.constant.SecurityConstants;
import com.cwz.core.utils.ip.IpUtils;
import com.cwz.core.utils.jwt.JwtHS512Utils;
import com.cwz.core.utils.servle.ServletUtils;
import com.cwz.core.utils.string.StringUtils;
import com.cwz.core.utils.uuid.IdUtils;
import com.cwz.redis.service.RedisService;
import com.cwz.security.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @program: w-demo
 * @description: token检验处理
 * @author: Wen
 **/
@Component
public class TokenService {
	@Autowired
	private RedisService redisService;

	private static final long MILLIS_SECOND = 1000;

	private static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

	private final static long expireTime = CacheConstants.EXPIRATION;

	private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;

	private final static Long MILLIS_MINUTE_TEN = CacheConstants.REFRESH_TIME * MILLIS_MINUTE;

	/**
	 * @Description: 创建令牌
	 * @Author: Wen
	 * @param loginUser:
	 * @return: java.util.Map<java.lang.String,java.lang.Object>
	 **/
	public Map<String, Object> createToken(LoginUser loginUser) {
		String token = IdUtils.fastUUID();
		loginUser.setToken(token);
		loginUser.setIpaddr(IpUtils.getIpAddr(ServletUtils.getRequest()));
		refreshToken(loginUser);

		// Jwt存储信息
		Map<String, Object> claimsMap = new HashMap<>();
		claimsMap.put(SecurityConstants.DETAILS_USER_ID, loginUser.getSysUser().getUserId());
		claimsMap.put(SecurityConstants.DETAILS_USERNAME, loginUser.getSysUser().getUserName());
		claimsMap.put(SecurityConstants.USER_KEY, token);
		claimsMap.put(SecurityConstants.DETAILS_COMPANY, loginUser.getCompany());

		// 接口返回信息
		Map<String, Object> rspMap = new HashMap<>();
		rspMap.put("access_token", JwtHS512Utils.createToken(claimsMap));
		rspMap.put("expires_in", expireTime);
		return rspMap;
	}

	/**
	 * @Description: 获取用户身份信息
	 * @Author: Wen
	 * @return: com.cwz.api.model.LoginUser
	 **/
	public LoginUser getLoginUser() {
		return getLoginUser(ServletUtils.getRequest());
	}

	/**
	 * @Description: 获取用户身份信息
	 * @Author: Wen
	 * @param request:
	 * @return: com.cwz.api.model.LoginUser
	 **/
	public LoginUser getLoginUser(HttpServletRequest request) {
		// 获取请求携带的令牌
		String token = SecurityUtils.getToken(request);
		return getLoginUser(token);
	}

	/**
	 * @Description: 获取用户身份信息
	 * @Author: Wen
	 * @param token:
	 * @return: com.cwz.api.model.LoginUser
	 **/
	public LoginUser getLoginUser(String token) {
		LoginUser user = null;
		try {
			if (StringUtils.isNotEmpty(token)) {
				String userKey = JwtHS512Utils.getUserKey(token);
				user = redisService.getCacheObject(getTokenKey(userKey));
				return user;
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return user;
	}

	/**
	 * @Description: 设置用户身份信息
	 * @Author: Wen
	 * @param loginUser:
	 * @return: void
	 **/
	public void setLoginUser(LoginUser loginUser) {
		if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken())) {
			refreshToken(loginUser);
		}
	}

	/**
	 * @Description: 删除用户缓存信息
	 * @Author: Wen
	 * @param token:
	 * @return: void
	 **/
	public void delLoginUser(String token) {
		if (StringUtils.isNotEmpty(token)) {
			String userKey = JwtHS512Utils.getUserKey(token);
			redisService.deleteObject(getTokenKey(userKey));
		}
	}

	/**
	 * @Description: 验证令牌有效期，相差不足120分钟，自动刷新缓存
	 * @Author: Wen
	 * @param loginUser:
	 * @return: void
	 **/
	public void verifyToken(LoginUser loginUser) {
		long expireTime = loginUser.getExpireTime();
		long currentTime = System.currentTimeMillis();
		if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
			refreshToken(loginUser);
		}
	}

	/**
	 * @Description: 刷新令牌有效期
	 * @Author: Wen
	 * @param loginUser:
	 * @return: void
	 **/
	public void refreshToken(LoginUser loginUser) {
		loginUser.setLoginTime(System.currentTimeMillis());
		loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
		// 根据 uuid 将 loginUser 缓存
		String userKey = getTokenKey(loginUser.getToken());
		redisService.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
	}

	/**
	 * @Description: token 的键名
	 * @Author: Wen
	 * @param token:
	 * @return: java.lang.String
	 **/
	private String getTokenKey(String token) {
		return ACCESS_TOKEN + token;
	}

}
